package org.hcf.api.tencent.callback;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hcf.api.base.Const;
import org.hcf.api.base.Helper;
import org.hcf.api.base.SnowflakeUtils;
import org.hcf.api.tencent.callback.info.group.base.MessageBody;
import org.hcf.api.tencent.callback.info.content.TEXT;
import org.hcf.api.tencent.callback.info.group.GroupChatMsgInfo;
import org.hcf.api.intf.ICallBack;
import org.hcf.data.RedisUtils;
import org.hcf.data.cache.CacheConfig;
import org.hcf.data.cache.Caches;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Data
/** 发送群消息回调 */
public class CallbackGroupMsgHandler implements ICallBack {
    @Override
    public String getCommand() {
        return Const.CMD.GROUP_SEND_MSG_AFTER;// "Group.CallbackAfterSendMsg";
    }

    @Override
    public JSONObject action(JSONObject data) {
        log.info("准备处理发送群消息回调信息:" + data);
        GroupChatMsgInfo info = data.toJavaObject(GroupChatMsgInfo.class);
        log.info("解析群消息:" + JSONObject.toJSON(info));
        if (!getCommand().equals(info.getCallbackCommand())) {
            log.error("群聊消息中[" + data.getString("CallbackCommand") + "]命令不匹配");
//            return Helper.toSuccess();
        }
        HashSet<Long> userIds = RedisUtils.getGA2UID(info.getGroupId());
        if (userIds == null || userIds.size() == 0) {
            log.error(JSONObject.toJSONString(RedisUtils.getGA2UID().keys()) + "群[" + info.getGroupId() + "]聊消息" + data + "中没有PLUGIN用户,无需处理");
            return Helper.toSuccess();
        }
        long msgId = SnowflakeUtils.nextId();
        for (MessageBody messageBody : info.getMsgBody()) {
            if (messageBody.getMsgType().equals(Const.MSG_TYPE.TEXT)) {
                long from = Long.parseLong(info.getFrom_Account());
                long to = RedisUtils.getGroupIDByAccount(info.getGroupId());
                TEXT text = JSONObject.parseObject(messageBody.getMsgContent().toString(), TEXT.class);
                for (Long userId : userIds) {
                    Helper.sendToPlugin(from, userId, to + "@chatroom", text.getText(), msgId);
                }

//                sendToPlugin(from, to, text, info.getGroupId(), info.getMsgSeq());
            } else log.error("群消息[" + info.getMsgSeq() + "]类型[" + messageBody.getMsgType() + "]不处理");
        }
        return Helper.toSuccess();
    }


//    void sendToPlugin(long from, long to, TEXT text, String groupAccount, long msgId) {
//        Set<Long> ids = Helper.getPluginUserIds();
//        for (long uid : ids) {
//            Set<Long> groupIds = Caches.getCache(CacheConfig.PLUGIN_USER_GROUP).get(String.valueOf(uid), HashSet.class);
//            if (groupIds != null && groupIds.contains(to)) {
//        Helper.sendToPlugin(from, uid, to + "@chatroom", text.getText(), msgId);
//            }
//        }
//    }
}
